package com.itheima.web.admin;

import com.github.pagehelper.PageInfo;
import com.itheima.model.ResponseData.ResponseData;
import com.itheima.model.ResponseData.StaticticsBo;
import com.itheima.model.domain.*;
import com.itheima.service.IArticleService;
import com.itheima.service.ISiteService;
import com.itheima.service.IUserService;
import com.itheima.service.impl.BusGoodsSevice;
import com.itheima.service.impl.BusUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.Message;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Classname AdminController
 * @Description 后台管理模块
 * @Date 2023-5-14 10:39
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private ISiteService siteServiceImpl;
    @Autowired
    private IArticleService articleServiceImpl;
    @Autowired
    private IUserService userServiceImpl;
    @Autowired
    private BusUserService busUserService;
    @Autowired
    private BusGoodsSevice busGoodsSevice;


    // 管理中心起始页
    @GetMapping(value = {"", "/index"})
    public String index(HttpServletRequest request) {
        // 获取最新的5篇博客、评论以及统计数据
        List<Article> articles = siteServiceImpl.recentArticles(5);
        List<Comment> comments = siteServiceImpl.recentComments(5);
        StaticticsBo staticticsBo = siteServiceImpl.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments", comments);
        request.setAttribute("articles", articles);
        request.setAttribute("statistics", staticticsBo);
        return "back/index";
    }

    // 向文章发表页面跳转
    @GetMapping(value = "/article/toEditPage")
    public String newArticle( ) {
        return "back/article_edit";
    }
    // 发表文章
    @PostMapping(value = "/article/publish")
    @ResponseBody
    public ResponseData publishArticle(Article article) {
        if (StringUtils.isBlank(article.getCategories())) {
            article.setCategories("默认分类");}
        try {
            articleServiceImpl.publish(article);
            logger.info("文章发布成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("文章发布失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }
    // 跳转到后台文章列表页面
    @GetMapping(value = "/article")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Article> pageInfo = articleServiceImpl.selectArticleWithPage(page, count);
        request.setAttribute("articles", pageInfo);
        return "back/article_list";
    }

    // 向文章修改页面跳转
    @GetMapping(value = "/article/{id}")
    public String editArticle(@PathVariable("id") String id, HttpServletRequest request) {
        Article article = articleServiceImpl.selectArticleWithId(Integer.parseInt(id));
        request.setAttribute("contents", article);
        request.setAttribute("categories", article.getCategories());
        return "back/article_edit";
    }

    // 文章修改处理
    @PostMapping(value = "/article/modify")
    @ResponseBody
    public ResponseData modifyArticle(Article article) {
        try {
            articleServiceImpl.updateArticleWithId(article);
            logger.info("文章更新成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("文章更新失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }

    // 文章删除
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public ResponseData delete(@RequestParam int id) {
        try {
            articleServiceImpl.deleteArticleWithId(id);
            logger.info("文章删除成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("文章删除失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }
    //用户信息列表
    @GetMapping(value = "/user")
    public String UserIndex(@RequestParam(value = "page", defaultValue = "1") int page,
                            @RequestParam(value = "count", defaultValue = "10") int count,
                            HttpServletRequest request){
        PageInfo<User> users =userServiceImpl.selectUserWithPage(page,count);
        request.setAttribute("users",users );
        return "back/user_list";
    }

    //用户删除
    @PostMapping(value = "/user/delete")
    @ResponseBody
    public ResponseData deleteUserWithId(@RequestParam int id) {
        try {
            userServiceImpl.deleteUserWithId(id);
            logger.info("用户删除成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("用户删除失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }

    //用户权限更新
    @PostMapping(value = "/user/update")
    @ResponseBody
    public ResponseData saveUser(@RequestParam int id) {
        try {
            userServiceImpl.updateAuthorityWithId(id);
            logger.info("权限更新成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("权限更新失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }
    //用户信息编辑
    @GetMapping(value = "/user/edit/{id}")
    public String editUser(@PathVariable("id") int id,Model model) {
        User user = userServiceImpl.selectUserWithId(id);
        model.addAttribute("user", user);
        return "back/user_edit";
    }
    //用户信息保存
    @GetMapping ("/user/saveUser")
    @ResponseBody
    public String saveUser(User user) {
        try {
            userServiceImpl.updateUserWithId(user);
            logger.info("用户信息更新成功");
            return "User information saved successfully";
        } catch (Exception e) {
            logger.error("用户信息更新失败，错误信息: "+e.getMessage());
            return "comm/error_404";
        }
    }
    //用户信息搜索
    @GetMapping("/user/search")
    public String searchUsers(@RequestParam("keyword") String keyword, Model model) {
        List<User> userList = userServiceImpl.searchUsers(keyword);
        model.addAttribute("userList", userList);
        return "back/search_list";
    }
    //商户信息
    @GetMapping("/bususer")
    public String BusUserIndex(HttpServletRequest request){
        List<BusUser> users =busUserService.findAll();
        request.setAttribute("users",users );
        return "back/bus_user_list";
    }
    //商户信息搜索
    @GetMapping("/bususer/search")
    public String searchBusUsers(@RequestParam("keyword") String keyword, Model model){
        List<BusUser> busUserList=busUserService.searchByUsername(keyword);
        model.addAttribute("busUserList",busUserList);
        return "back/search_bus_list";
    }

    //商户信息删除
    @PostMapping(value = "/bususer/delete")
    @ResponseBody
    public ResponseData deleteBusUserWithId(@RequestParam int id) {
        try {
            busUserService.deleteBusUserById(id);
            logger.info("商户删除成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("商户删除失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }
    //商户信息编辑
    @GetMapping(value = "/bususer/edit/{id}")
    public String editBusUser(@PathVariable("id") int id,Model model) {
        BusUser bususer = busUserService.findUserById(id);
        model.addAttribute("bususer", bususer);
        return "back/bus_user_edit";
    }
    //商户信息保存
    @GetMapping (value ="/bususer/saveUser")
    @ResponseBody
    public String saveBusUser(BusUser busUser) {
        try {
            busUserService.updateBusUserInfo(busUser);
            logger.info("商户信息更新成功");
            return "User information saved successfully";
        } catch (Exception e) {
            logger.error("商户信息更新失败，错误信息: "+e.getMessage());
            return "comm/error_404";
        }
    }
    //商品信息
    @GetMapping(value ="/goods")
    public String GoodsIndex(HttpServletRequest request){
        List<BusGoodsInfo> goodsInfos =busGoodsSevice.findAll();
        request.setAttribute("goodsInfos",goodsInfos );
        return "back/bus_goods_list";
    }
    //删除商品信息
    @PostMapping(value = "/goods/delete")
    @ResponseBody
    public ResponseData deleteGoodsInfoById(@RequestParam int id) {
        try {
            busGoodsSevice.deleteBusGoodsInfoById(id);
            logger.info("商品删除成功");
            return ResponseData.ok();
        } catch (Exception e) {
            logger.error("商品删除失败，错误信息: "+e.getMessage());
            return ResponseData.fail();
        }
    }
    //商品信息搜索
    @GetMapping("/goods/search")
    public String searcGoodsInfo(@RequestParam("keyword") String keyword, Model model){
        List<BusGoodsInfo> busGoodsInfoList=busGoodsSevice.searchByGoodsname(keyword);
        model.addAttribute("busGoodsInfoList",busGoodsInfoList);
        return "back/search_goods_list";
    }

    //商户信息编辑
    @GetMapping(value = "/goods/edit/{id}")
    public String editGoodsInfo(@PathVariable("id") int id,Model model) {
        BusGoodsInfo busGoodsInfo = busGoodsSevice.findBusGoodsById(id);
        model.addAttribute("busGoodsInfo", busGoodsInfo);
        return "back/bus_goods_edit";
    }

    //商户信息保存
    @GetMapping (value ="/goods/saveGoods")
    @ResponseBody
    public String saveGoodsInfo(BusGoodsInfo busGoodsInfo) {
        try {
            busGoodsSevice.updateBusGoodsInfo(busGoodsInfo);
            logger.info("商品信息更新成功");
            return "Goods information saved successfully";
        } catch (Exception e) {
            logger.error("商品信息更新失败，错误信息: "+e.getMessage());
            return "comm/error_404";
        }
    }

    //网站系统设置信息
    @GetMapping(value = "/setting")
    public String SettingInfo(){
        return "back/setting";
    }


}

